#include <cmath>
#include <ctype.h>
#include <string>
#include <SDL.h>

#include "type.hpp"
#include "textbuffer.hpp"
#include "textfield.hpp"
#include "scrollbox.hpp"
 
#ifdef NATIVE_BUILD
	#include <sys/types.h>
	#define sleep_(a) usleep(a*1000)
#else
	#include <time.h>
	void sleep_(unsigned int mseconds)
		{
			clock_t goal = mseconds + clock();
			while (goal > clock());
		};
#endif




 
int main(int argc, char *argv[])
{
  
    static const int width = 640;
    static const int height = 480;

	

    
 
    if (SDL_Init(SDL_INIT_VIDEO) != 0)
    	return 1;
 

    atexit(SDL_Quit);   

    SDL_Surface *screen = SDL_SetVideoMode(width, height, 0, SDL_DOUBLEBUF);
 
	FontMap* fMap = new FontMap();
	fMap->Prepare("./fonts/prf.ttf",40);
	TextBuffer* tb = new TextBuffer();
	FILE* f = fopen("textfield.hpp","r");
    fseek(f,0,SEEK_END);
    int fsize = ftell(f);
    fseek(f,0,SEEK_SET);
    char* txt = new char[fsize];
    fread(txt, 1, fsize, f);
    fclose(f);
    std::string text = std::string(txt);    
	tb->LoadFromMemory( reinterpret_cast<unsigned char*>(txt) ,fsize);
	delete[] txt;

	ScrollBox * sb = new ScrollBox(NULL, screen);
	sb->SetPosition(50, 50);
	sb->SetSize(500, 300);

	TextField * tf = new TextField(NULL, screen, fMap);
	tf->SetBuffer(tb);

	sb->AddChild(tf);
	
	
    
	if (screen == NULL)
        return 2;

	Vec<int,2> npos;
	npos.Set(0,0);
	npos.Set(1,0);
	bool running = true;
    while(running)
    {
        SDL_Event event; 
        while(SDL_PollEvent(&event))
        {
            if(event.type == SDL_QUIT)
			{
                return 0;
			}
			else if (event.type == SDL_KEYDOWN)
			{
				SDLKey keyPressed = event.key.keysym.sym;
				sb->KeyDown(keyPressed);
				switch (keyPressed)
				{
				case SDLK_ESCAPE:
				running = false;
				break;
				}
			}
			else if (event.type == SDL_MOUSEMOTION)
			{
				
				printf("Mouse motion x:%d, y:%d\n", event.motion.x, event.motion.y );
			}
			else if (event.type == SDL_MOUSEBUTTONUP)
			{
				sb->MouseUp(event.button.x, event.button.y, event.button.button);
				printf("Mouse pressed x:%d, y:%d\n", event.button.x, event.button.y );
			}
			else if (event.type == SDL_MOUSEBUTTONDOWN)
			{
				sb->MouseDown(event.button.x, event.button.y, event.button.button);
				printf("Mouse pressed x:%d, y:%d\n", event.button.x, event.button.y );
			}

        }
		
		tf->Update();

        SDL_LockSurface(screen);
 
		sb->Render(npos);
 
        SDL_FreeSurface(screen);
 
        SDL_Flip(screen);
		sleep_(50);
    }
 
    return 0;
}
